package com.jmb.apiplatform.cores.http;


import com.jmb.apiplatform.constant.Constants;
import com.jmb.apiplatform.mapper.HttpSettingMapper;
import com.jmb.apiplatform.pojo.HttpSettingTO;
import com.jmb.apiplatform.pojo.HttpSettingVO;
import lombok.SneakyThrows;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.KeyStore;
import java.util.List;


@Component
public class RequestFactory {
    @Autowired
    private HttpSettingMapper httpSettingMapper;
    // 日志类
    private static final Logger log= LoggerFactory.getLogger(RequestFactory.class);


    /**
     * 支持http https 底层基于HttpsURLConnection
     * @return SimpleClientHttpRequestFactory
     */
    public SimpleClientHttpRequestFactory byURLConnection(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(){
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                try {
                    if (!(connection instanceof HttpURLConnection)){
                        super.prepareConnection(connection,httpMethod);
                    }
                    if (connection instanceof HttpURLConnection){
                        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        // 信任任何链接
                        TrustStrategy anyTrustStrategy = (x509Certificates, s) -> true;
                        SSLContext ctx = SSLContexts.custom().setProtocol("TLS").loadTrustMaterial(trustStore, anyTrustStrategy).build();
                        ((HttpsURLConnection)connection).setSSLSocketFactory(ctx.getSocketFactory());
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                        super.prepareConnection(httpsConnection,httpMethod);
                    }
                }catch (Exception e){
                    log.info("代理设置失败,打印错误信息：",e);
                }
            }
        };
        Proxy proxy = proxy4HttpURLConnection();
        if (proxy!=null){
            factory.setProxy(proxy);
        }
        factory.setReadTimeout(readTimeout());
        factory.setConnectTimeout(connectTimeout());
        return factory;

    }
    /**
     * 支持http https 底层基于HttpClient
     * @return HttpComponentsClientHttpRequestFactory
     */
    public HttpComponentsClientHttpRequestFactory byHttpClient()  {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
        } catch (Exception e) {
            log.info("代理设置失败,打印错误信息：",e);
        }
        HttpClientBuilder builder = HttpClients.custom();
        builder.setProxy(proxy4HttpClient());
        CloseableHttpClient closeableHttpClient = builder.build();
        factory.setHttpClient(closeableHttpClient);
        factory.setReadTimeout(readTimeout());
        factory.setConnectTimeout(connectTimeout());
        return factory;
    }

    @SneakyThrows
    private HttpHost proxy4HttpClient() {
        HttpSettingVO proxy = null;
        HttpSettingTO httpSettingTO = new HttpSettingTO();
        httpSettingTO.setStatusId((byte)0);
        httpSettingTO.setType((byte)0);
        List<HttpSettingVO> list = httpSettingMapper.selectHttpSetting(httpSettingTO);
        if (!list.isEmpty()) {
            proxy = list.get(0);
        }
        if (proxy != null) {
            return HttpHost.create(proxy.getValue());
        }
        return null;
    }
    /**
     * 基于HttpsURLConnection的代理
     * @return Proxy
     */
    private Proxy proxy4HttpURLConnection() {
        HttpSettingVO proxy = null;
        HttpSettingTO httpSettingDTO = new HttpSettingTO();
        httpSettingDTO.setStatusId((byte)0);
        httpSettingDTO.setType((byte)0);
        List<HttpSettingVO> list = httpSettingMapper.selectHttpSetting(httpSettingDTO);
        if (!list.isEmpty()) {
            proxy = list.get(0);
        }
        if (proxy != null) {
            String[] domain = proxy.getValue().split(":");
            String host = domain[0];
            int port = Integer.parseInt(domain[1]);
            return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
        }
        return null;
    }

    private Integer getTimeout(Byte type,Integer defaultValue){
        HttpSettingTO httpSettingTO= new HttpSettingTO();
        // 默认0
        httpSettingTO.setStatusId(Constants.STATUS_ACTIVE);
        httpSettingTO.setType(type);
        List<HttpSettingVO> httpSettingTOList = httpSettingMapper.selectHttpSetting(httpSettingTO);
        if (httpSettingTOList.isEmpty()){
            return defaultValue;
        }
        String value = httpSettingTOList.get(0).getValue();
        if (value==null || value.trim().isEmpty()){
            return defaultValue;
        }
        // 超时时间
        int timeout = Integer.parseInt(value.trim());
        try {
            if (timeout < 0) {
                return defaultValue;
            }return timeout;
        }catch (NumberFormatException e){
            // 记录日志
            return defaultValue;
        }
    }
    private Integer connectTimeout(){
        return getTimeout(Constants.TYPE_CONNECT_TIMEOUT, Constants.DEFAULT_CONNECT_TIMEOUT);
    }
    private Integer readTimeout(){
        return getTimeout(Constants.TYPE_READ_TIMEOUT, Constants.DEFAULT_READ_TIMEOUT);
    }
}
